﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SendMailServer.WebSocket
{
    internal class WebSocketHelper
    {
        private static string m_webHookFile = @"D:\Program Files\SendMailServer\agcim.tools.forwebhook\msg.txt";
        public static ResMsg SendWebhookMsg(string key, string filterStr)
        {
            if (File.Exists(m_webHookFile) == false) return null;
            if (key != "SendWebhookMsg")
            {
                return null;
            }
            try
            {
                if (filterStr == null) { filterStr = ""; }
                if (filterStr.EndsWith(",desktop"))
                {
                    filterStr = filterStr.Substring(0, filterStr.Length - ",desktop".Length);
                }

                File.AppendAllText(m_webHookFile, "\r\n" + filterStr);
                var batFile = Path.Combine(Path.GetDirectoryName(m_webHookFile), "a.bat");

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("chcp 65001");
                stringBuilder.AppendLine(m_webHookFile.Substring(0, 2));
                stringBuilder.AppendLine("CD " + Path.GetDirectoryName(m_webHookFile));
                stringBuilder.AppendLine("git add msg.txt");
                stringBuilder.AppendLine("git commit -m \"" + filterStr + "\"");
                stringBuilder.AppendLine("git push origin master");

                File.WriteAllText(batFile, stringBuilder.ToString());
                
                return new ResMsg()
                {
                    AppName = "desktop",
                    Content = "SendWebhookMsgOK",
                    IsOk = true,
                    UseSelfResponse = true,
                };
            }
            catch (Exception err)
            {
                Logger.WriteLine("SendWebhookMsg错误：" + err.Message + ";" + err.StackTrace);
            }
            return null;
        }
    }
}
